/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.mybatis.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlInjectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.Setter;

/**
 * 请求查询的时间范围
 *
 * @author zeng
 */
@Data
public class DateQuery<T> {
  @Schema(description = "开始时间")
  private String startDate;

  @Schema(description = "结束时间")
  private String endDate;

  @Schema(description = "每页大小")
  protected long size = 10;

  @Schema(description = "当前页")
  protected long current = 1;

  @Schema(description = "排序字段信息")
  @Setter
  protected List<OrderItem> orders = new ArrayList<>();

  /**
   * 转换为分页对象
   *
   * @return 分页对象
   */
  public IPage<T> toPage() {
    Page<T> page = new Page<>();
    page.setSize(size);
    page.setCurrent(current);
    page.setOrders(orders);
    return page;
  }

  /**
   * 构建查询条件
   *
   * @param entity 查询实体
   * @param timeFrame 时间范围查询
   * @return QueryWrapper
   */
  public <E extends T> QueryWrapper<T> query(E entity, Boolean timeFrame) {
    QueryWrapper<T> queryWrapper = new QueryWrapper<>(entity);
    if (timeFrame) {
      if (ObjectUtils.isNotEmpty(this.getStartDate())
          && !SqlInjectionUtils.check(this.getStartDate())) {
        queryWrapper.ge("create_at", this.getStartDate());
      }
      if (ObjectUtils.isNotEmpty(this.getEndDate())
          && !SqlInjectionUtils.check(this.getEndDate())) {
        queryWrapper.le("create_at", this.getEndDate());
      }
    }
    return queryWrapper;
  }

  public <E extends T> QueryWrapper<T> query(E entity) {
    return query(entity, true);
  }
}
